package com.sanjiahantang.youjiaclient.module.common.presenters;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioButton;

import com.sanjiahantang.uilibrary.drawable.CartDrawable;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.common.beans.StringBean;
import com.sanjiahantang.youjiaclient.module.common.models.IMainModel;
import com.sanjiahantang.youjiaclient.module.common.models.impl.MainModel;
import com.sanjiahantang.youjiaclient.module.common.views.MainView;
import com.sanjiahantang.youjiaclient.module.common.views.impl.HomeFragment;
import com.sanjiahantang.youjiaclient.utils.SPUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import static com.sanjiahantang.youjiaclient.config.StaticValue.RESPONSE_CODE_SUC;

/**
 * Created by zy on 2017/8/31.
 */

public class MainPresenter extends BaseMvpPresenter<MainView> implements CallBack<StringBean> {
    private IMainModel mainModel;
    private static FragmentManager fMgr;
    private PushAgent mPushAgent;
    public Handler handler = new Handler();
    private String goodsNum = "";
    public MainPresenter(){
        // 获取FragmentManager实例
        mainModel = new MainModel();
    }

    public void onLoad(Context context){
        mPushAgent = PushAgent.getInstance(context);                                                  //开启推送服务
        ConfigValue.DATA_KEY = (String) SPUtils.get(context, SPConfig.KEY,"");
        //初始化个人信息
        SPUtils.put(context, SPConfig.FRAGMENT, 0);
        mPushAgent.onAppStart();
        //开启推送并设置注册的回调处理
        mPushAgent.enable(mRegisterCallback);
    }

    @Override
    public void onSuccess(StringBean response, Context context, Object tag) {
        if (response.getCode() == RESPONSE_CODE_SUC)
            setCartGoodsNums(context,response.getData());
    }

    @Override
    public void onFailure(String message) {

    }



    class MainReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConfigValue.ACTION_ALTER_CARTGOODS_NUMS)) {
                int addNum = intent.getIntExtra("addGoodsNums", 0);
                String total = intent.getStringExtra("cartgoodsnum");
                int homeFlag = intent.getIntExtra("home",0);
                if (addNum != 0)
                    addCartGoodsNums(addNum);
                if (null != total && !total.equals(""))
                    setCartGoodsNums(context,total);
                if(homeFlag != 0){
                    mView.isFirstPage();
                }
            }
        }
    }




    public void registerBroadcastReceiver(Context context) {

        //注册广播
        //初始化的时候判断是否为空，为空才将它初始化，这样就能保证始终存在一个。

        if (ConfigValue.hasRegisterReceiver == false){
            IntentFilter mIntentFilter = new IntentFilter();
            mIntentFilter.addAction(ConfigValue.ACTION_ALTER_CARTGOODS_NUMS);
            context.registerReceiver(new MainReceiver(), mIntentFilter);
            ConfigValue.hasRegisterReceiver = true;
        }


    }

    public void onResume(Context context){
        if (fMgr == null){
            int flag = (int) SPUtils.get(context,SPConfig.FRAGMENT,0);
            // 获取FragmentManager实例
            fMgr = mView.getFManager();
            mView.dealBottomButtonsClickEvent();
            mView.startFragment(flag);
        }
    }

    public void startFragment(Class<Fragment> fragmentClass, int rootId, String tag){

        FragmentTransaction ft = fMgr.beginTransaction();
        startFragment(ft,fragmentClass,rootId,tag);
    }
    private void startFragment(FragmentTransaction ft, Class<Fragment> fragment,int rootId,String tag){
        try {
            ft.replace(rootId, fragment.newInstance(), tag);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        ft.addToBackStack(tag);
        ft.commit();
    }

    public void fragmentSelected(Context context,Class<Fragment> fragmentClass,int rootId,String tag,int index,boolean flag){
        if (fMgr == null){
            initFragment(R.id.fragmentRoot,MainView.TAG_HOME);
        }
        FragmentTransaction ft = fMgr.beginTransaction();
        SPUtils.put(context, SPConfig.FRAGMENT, index);
        ConfigValue.iconFlag = flag?1:0;
        CartDrawable cartDrawable = new CartDrawable(context,ConfigValue.iconFlag);
        cartDrawable.setCatNum(goodsNum);

        if (fMgr.findFragmentByTag(tag) != null) {
            ft.replace(rootId,fMgr.findFragmentByTag(tag), tag);
            ft.commit();
        } else {
            startFragment(ft,fragmentClass,rootId,tag);

        }
        mView.setButtonImage(cartDrawable);
    }

    //修改购物车角标回调
    public void setCartGoodsNums(Context context,String nums) {
        goodsNum = nums;
        CartDrawable cartDrawable = new CartDrawable(context,ConfigValue.iconFlag);
        cartDrawable.setCatNum(nums);
        mView.setButtonImage(cartDrawable);
    }

    /**
     *    此处是注册的回调处理
     *    参考集成文档的1.7.10
     *    http://dev.umeng.com/push/android/integration#1_7_10
     */
    public IUmengRegisterCallback mRegisterCallback = new IUmengRegisterCallback() {

        @Override
        public void onRegistered(String registrationId) {
            // TODO Auto-generated method stub
            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    if (mPushAgent.isRegistered()) {
                        //成功
                    }
                }
            });
        }
    };

    /**
     * 初始化首个Fragment
     */
    public void initFragment(int fragmentId,String tag) {
        fMgr = mView.getFManager();
        FragmentTransaction ft = fMgr.beginTransaction();
        HomeFragment homeFragment=new HomeFragment();
        ft.add(fragmentId, homeFragment, tag);
        ft.addToBackStack(tag);
        ft.commit();
    }




    /**
     *
     * @param firstButton
     * @param tag
     * @return
     */
    public boolean isFirstPage(Context context,RadioButton firstButton,String tag){
        boolean result = fMgr != null && fMgr.findFragmentByTag(tag) != null
                && !fMgr.findFragmentByTag(tag).isResumed();
        if(result){
            firstButton.toggle();
            SPUtils.put(context, SPConfig.FRAGMENT, 0);
        }

        return result;
    }
    /**
     * 后退事件
     */
    public void onBackPressed(){
        if (!mView.isFirstPage()) {
            mView.close();
        }
    }





    public void getPersonalInfo(final Context context){
        //网络检查
        if (Utils.NO_NETWORK_STATE == Utils.isNetworkAvailable(context)) {
            Utils.showToast(context,"网络好像阻塞了哦，亲");
        }else{
            mainModel.getPersonalInfo(context, getDefaultMD5Params("goods", "cartnum"), this);
        }
    }



    //角标增加，用于在商品详情页增加商品至购物车时调用
    public void addCartGoodsNums(int nums) {
        int now = Integer.parseInt(goodsNum) + nums;
        goodsNum = String.valueOf(now);
        CartDrawable cartDrawable = mView.getCartDrawable(1);
        cartDrawable.addNums(nums);
        cartDrawable.start();
    }

    @Override
    public void detach() {
        super.detach();
        fMgr = null;
    }
}
